﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Globalization;
using System.Net;
using System.Net.Sockets;

namespace I_Archives.Read.API
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GolbalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GolbalExceptionFilter> _logger;

        public GolbalExceptionFilter(ILogger<GolbalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            // 获取本机IP地址
            var hostName = Dns.GetHostName();
            var hostEntry = Dns.GetHostEntry(hostName);
            var ipAddress = hostEntry.AddressList.FirstOrDefault(options =>
            {
                return options.AddressFamily == AddressFamily.InterNetwork;
            });

            _logger.LogError(ipAddress + context.Exception.StackTrace[..50] + "凯哥，报错了，报错了！");
            context.ExceptionHandled = true;
        }
    }
}
